package com.team24.hotel.controller;

import com.github.pagehelper.Page;
import com.team24.hotel.domain.*;
import com.team24.hotel.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/hotel")
public class HotelController {
    @Autowired
    private HotelService hotelService;
    @Autowired
    private CountryService countryService;
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private CityService cityService;
    @Autowired
    private HotelImageService hotelImageService;
    @Autowired
    private RoomImageService roomImageService;
    @Autowired
    private  RoomService roomService;
    @Autowired
    private  BreakfastService breakfastService;
    @Autowired
    private  BreakfastImageService breakfastImageService;
    @GetMapping("/list")
    public String listHotelPage(Model model){
        List<Hotel> hotels=hotelService.listHotel();
        model.addAttribute("hotels",hotels);
        return "hotelList";
    }
    @GetMapping("/edit")
    public String editHotelPage(@RequestParam("id")int id,Model model){
        Hotel hotel=hotelService.findHotelByPrimaryKey(id);
        int oldProvinceId=cityService.findProvinceId(hotel.getCityId());
        int oldCountryId=provinceService.findCountryId(oldProvinceId);
        List<Country> countries = countryService.findAll();
        List<Province> provinces = provinceService.findAllByCountryId(oldCountryId);
        List<City> cities = cityService.findAllByProvinceId(oldProvinceId);
        List<HotelImage>hotelImages=hotelImageService.listImage(id);
        model.addAttribute("countries",countries);
        model.addAttribute("provinces",provinces);
        model.addAttribute("cities",cities);
        model.addAttribute("oldProvinceId",oldProvinceId);
        model.addAttribute("oldCountryId",oldCountryId);
        model.addAttribute("hotel",hotel);
        model.addAttribute("hotelImages",hotelImages);
        return "hotelUpdate";
    }
    @PostMapping("/edit")
    public String updateHotel(Hotel hotel){
        City city=cityService.findTotalNameByPrimaryKey(hotel.getCityId());
        String location=city.getCountryName()+" "+city.getProvinceName()+" "+city.getCityName();
        hotel.setHotelLocation(location);
        int updated= hotelService.updateHotel(hotel);
        if(updated>0) {
            return "redirect:/hotel/list";
        } else {
            return "redirect: error";
        }
    }
    @RequestMapping("/addImage")
    public String addHotelImage(@RequestParam("file")MultipartFile []file,@RequestParam("hotelId")int hotelId) throws FileNotFoundException {
        String path= ResourceUtils.getURL("src/main/resources/static/img/").getPath();
        path=path.substring(1);
        System.out.println(path);
        int len=file.length;
        for (int i=0;i<len;i++){
            String fileName=file[i].getOriginalFilename();
            String suffixName=fileName.substring(fileName.lastIndexOf("."));
            fileName= UUID.randomUUID()+suffixName;
            File dest=new File(path+fileName);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }    try {
                file[i].transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            HotelImage hotelImage=new HotelImage();
            hotelImage.setImageName(fileName);
            hotelImage.setHotelId(hotelId);
            hotelImageService.saveHotelImage(hotelImage);
        }
        return "redirect:/hotel/edit?id="+hotelId;
    }
    @GetMapping("/add")
    public String addHotel(Model model){
        List<Country> countries=countryService.findAll();
        model.addAttribute("countries",countries);
        List<Province> provinces=provinceService.findAllByCountryId(countries.get(0).getCountryId());
        model.addAttribute("provinces",provinces);
        List<City> cities=cityService.findAllByProvinceId(provinces.get(0).getProvinceId());
        model.addAttribute("cities",cities);
        model.addAttribute("hotel",new Hotel());
        return "hotelAdd";
    }
    @PostMapping("/add")
    public String saveHotel(Hotel hotel, @RequestParam("file")MultipartFile []file, HttpServletRequest request) throws FileNotFoundException {
        City city=cityService.findTotalNameByPrimaryKey(hotel.getCityId());
        String location=city.getCountryName()+" "+city.getProvinceName()+" "+city.getCityName();
        hotel.setHotelLocation(location);
        String path= ResourceUtils.getURL("src/main/resources/static/img/").getPath();
        path=path.substring(1);
        System.out.println(path);
        int len=file.length;
        int insert=hotelService.insertHotel(hotel);
        int hotelId=hotelService.selectLastInsertId();
        for (int i=0;i<len;i++){
            String fileName=file[i].getOriginalFilename();
            String suffixName=fileName.substring(fileName.lastIndexOf("."));
            fileName= UUID.randomUUID()+suffixName;
            File dest=new File(path+fileName);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }    try {
                file[i].transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            HotelImage hotelImage=new HotelImage();
            hotelImage.setImageName(fileName);
            hotelImage.setHotelId(hotelId);
            hotelImageService.saveHotelImage(hotelImage);
        }
        if(insert>0) {
            return "redirect:/hotel/list";
        } else {
            return "redirect: error";
        }
    }
    @GetMapping("/delete")
    public  String deleteHotel(@RequestParam("id")int id) throws FileNotFoundException {
        String path= ResourceUtils.getURL("src/main/resources/static/img/").getPath();
        List<HotelImage>hotelImages=hotelImageService.listImage(id);
        for (HotelImage hotelImage:hotelImages
        ) {
            File file=new File(path+hotelImage.getImageName());
            if (file.exists()) file.delete();
        }
        List<Room>rooms=roomService.listRoom(id);
        for (Room room:rooms
        ) {
            List<RoomImage>roomImages=roomImageService.listRoomImage(room.getRoomId());
            for (RoomImage roomImage:roomImages
            ) {
                File file=new File(path+roomImage.getImageName());
                if (file.exists()) file.delete();
            }
        }
        List<Breakfast>breakfasts=breakfastService.listBreakfast(id);
        for (Breakfast breakfast:breakfasts
        ) {
            List<BreakfastImage>breakfastImages=breakfastImageService.listBreakfastImage(breakfast.getBreakfastId());
            for (BreakfastImage breakfastImage:breakfastImages
            ) {
                File file=new File(path+breakfastImage.getImageName());
                if (file.exists()) file.delete();
            }
        }
        int deleted=hotelService.deleteHotelByPrimaryKey(id);
        if(deleted>0) {
            return "redirect:/hotel/list";
        } else {
            return "redirect: error";
        }
    }

    @RequestMapping("/display")
    public String displayHotel(Model model, Integer pageNum, Integer pageSize){
        if (pageNum==null) pageNum=1;
        if (pageSize==null) pageSize=6;
        List<Hotel> hotels=hotelService.listHotelAndImage(pageNum,pageSize);
        int total=(int)((Page)hotels).getTotal();
        int num=total%pageSize==0?total/pageSize:total/pageSize+1;
        int pages[]=new int[num];
        for (int i = 0; i < num; i++) {
            pages[i]=i+1;
        }
        model.addAttribute("pages",pages);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("pageTotal",num);

        for (Hotel hotel:hotels
        ) {
            hotel.setHotelSign(0);//判断该酒店是否可以入住,0代表不可入住
            int roomsSign=0;//是否有空房，0代表无
            for (Room room:roomService.listRoom(hotel.getHotelId())
            ) {
                if (room.getRoomSign()==1) roomsSign++;
            }
            if(!roomService.listRoom(hotel.getHotelId()).isEmpty()|| roomsSign>0){
                hotel.setHotelSign(1);
            }
        }
        List<Country> countries=countryService.findAll();
        model.addAttribute("countries",countries);
        List<Province> provinces=provinceService.findAllByCountryId(countries.get(0).getCountryId());
        model.addAttribute("provinces",provinces);
        List<City> cities=cityService.findAllByProvinceId(provinces.get(0).getProvinceId());
        model.addAttribute("cities",cities);
        model.addAttribute("hotels",hotels);
        return "frontHotelList";
    }
    @RequestMapping("/detail")
    public String hotelDetail(@RequestParam("id")int id,Model model){
        Hotel hotel=hotelService.findHotelExtByPrimaryKey(id);
        System.out.println(hotel.getHotelLocation());
        List<Hotel> elseHotels=hotelService.listElseHotelAndImage(hotel.getHotelLocation(),id);
        List<HotelImage>hotelImages=hotelImageService.listImage(id);
        List<Room>rooms=roomService.roomAndImage(id);
        List<Breakfast>breakfasts=breakfastService.listBreakfastAndImage(id);
        model.addAttribute("elseHotels",elseHotels);
        model.addAttribute("hotelImages",hotelImages);
        model.addAttribute("rooms",rooms);
        model.addAttribute("hotel",hotel);
        model.addAttribute("breakfasts",breakfasts);
        return "frontHotelDetail";
    }

    @RequestMapping("/search")
    public String searchHotel(String countryId,String provinceId,String cityId,String minPrice,String maxPrice,String keyName,String keyLocation,String indexSearch,Model model,Integer pageNum,Integer pageSize){
        if (pageNum==null) pageNum=1;
        if (pageSize==null) pageSize=6;

        String countryName="";
        String provinceName="";
        String cityName="";

        //PSY 首页搜索
        if (indexSearch.equals("true")){
            List<Hotel> hotelList=hotelService.selectHotelByNameAndLocation(keyName,keyLocation,pageNum,pageSize);
            int total=(int)((Page)hotelList).getTotal();
            int num=total%pageSize==0?total/pageSize:total/pageSize+1;
            int pages[]=new int[num];
            for (int i = 0; i < num; i++) {
                pages[i]=i+1;
            }
            model.addAttribute("pages",pages);
            model.addAttribute("pageSize",pageSize);
            model.addAttribute("pageNum",pageNum);
            model.addAttribute("pageTotal",num);

            model.addAttribute("hotels",addHotelImage(hotelList));
            model.addAttribute("keyName",keyName);
            List<Country> countries=countryService.findAll();
            model.addAttribute("countries",countries);
            List<Province> provinces=provinceService.findAllByCountryId(countries.get(0).getCountryId());
            model.addAttribute("provinces",provinces);
            List<City> cities=cityService.findAllByProvinceId(provinces.get(0).getProvinceId());
            model.addAttribute("cities",cities);
            return "frontHotelList";
        }

        if(countryId.isEmpty()){
            //查询全部
        }else if(!countryId.isEmpty()&& (provinceId.isEmpty() || provinceId.equals("null"))){
            //按照国家
            Integer oldCountryId=Integer.parseInt(countryId);
            model.addAttribute("oldCountryId",oldCountryId);
            Country country=countryService.findByPrimaryKey(oldCountryId);
            countryName=country.getCountryName();
            model.addAttribute("provinceNoChoice","--未选择--");
            model.addAttribute("cityNoChoice","--未选择--");
        }else if(!countryId.isEmpty() && !provinceId.isEmpty() && (cityId.isEmpty() || cityId.equals("null"))){
            //按照国家和省
            Integer oldCountryId=Integer.parseInt(countryId);
            model.addAttribute("oldCountryId",oldCountryId);
            Integer oldProvinceId=Integer.parseInt(provinceId);
            model.addAttribute("oldProvinceId",oldProvinceId);
            Country country=countryService.findByPrimaryKey(oldCountryId);
            Province province=provinceService.findByPrimaryKey(oldProvinceId);
            countryName=country.getCountryName();
            provinceName=province.getProvinceName();
            model.addAttribute("cityNoChoice","--未选择--");
        }else if(!countryId.isEmpty() && !provinceId.isEmpty() && !cityId.isEmpty()){
            //按照国家 省 城市
            Integer oldCountryId=Integer.parseInt(countryId);
            model.addAttribute("oldCountryId",oldCountryId);
            Integer oldProvinceId=Integer.parseInt(provinceId);
            model.addAttribute("oldProvinceId",oldProvinceId);
            Integer oldCityId=Integer.parseInt(cityId);
            model.addAttribute("oldCityId",oldCityId);
            Country country=countryService.findByPrimaryKey(oldCountryId);
            Province province=provinceService.findByPrimaryKey(oldProvinceId);
            City city=cityService.findTotalNameByPrimaryKey(oldCityId);
            countryName=country.getCountryName();
            provinceName=province.getProvinceName();
            cityName=city.getCityName();
        }
        List<Hotel> hotelList=hotelService.selectHotelByExample(countryName,provinceName,cityName,keyName,pageNum,pageSize);
        int total=(int)((Page)hotelList).getTotal();
        List<Hotel> hotels=new ArrayList<>();
        for (Hotel hotel:hotelList
        ) {
            Hotel newHotel = hotelService.findHotelAndImageByPrimaryKey(hotel.getHotelId());
            if (minPrice.isEmpty() && maxPrice.isEmpty()) {
                Hotel hotelPrize=new Hotel();
                hotels.add(newHotel);
            } else if (minPrice.isEmpty() && !(maxPrice.isEmpty())) {
                if(newHotel.getHighPrize()==null) break;
                if (!(newHotel.getLowPrize() > (Integer.parseInt(maxPrice)))) {
                    hotels.add(newHotel);
                }
            } else if (!(minPrice.isEmpty()) && maxPrice.isEmpty()) {
                if (newHotel.getLowPrize()==null) break;
                if (!(newHotel.getHighPrize() < (Integer.parseInt(minPrice)))) {
                    hotels.add(newHotel);
                }
            } else if (!(minPrice.isEmpty()) && !(maxPrice.isEmpty())){
                if(newHotel.getLowPrize()==null || newHotel.getHighPrize()==null) break;
                if (!(newHotel.getLowPrize() > (Integer.parseInt(maxPrice))) && !(newHotel.getHighPrize() < (Integer.parseInt(minPrice)))) {
                    hotels.add(newHotel);
                }
            }else {
                total--;
            }
        }
        int num=total%pageSize==0?total/pageSize:total/pageSize+1;
        int pages[]=new int[num];
        for (int i = 0; i < num; i++) {
            pages[i]=i+1;
        }
        model.addAttribute("pages",pages);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("pageTotal",num);

        List<Country> countries=countryService.findAll();
        model.addAttribute("countries",countries);
        if(!countryId.isEmpty()){
            List<Province> provinces=provinceService.findAllByCountryId(Integer.parseInt(countryId));
            model.addAttribute("provinces",provinces);
        }
        if(!provinceId.isEmpty()){
            List<City> cities=cityService.findAllByProvinceId(Integer.parseInt(provinceId));
            model.addAttribute("cities",cities);
        }
        model.addAttribute("hotels",hotels);
        model.addAttribute("maxPrice",maxPrice);
        model.addAttribute("minPrice",minPrice);
        model.addAttribute("keyName",keyName);
        //把查出来的酒店再按照价格筛选
        return "frontSearchHotelList";
    }
    @RequestMapping("/deleteImage")
    @ResponseBody
    public  Boolean deleteImage(int[] imageId) throws FileNotFoundException {
        String path= ResourceUtils.getURL("src/main/resources/static/img/").getPath();
        for (int i=0;i<imageId.length;i++){
            HotelImage hotelImage = hotelImageService.findHotelImage(imageId[i]);
            File file=new File(path+hotelImage.getImageName());
            if (file.exists()) file.delete();
            hotelImageService.deleteHotelImage(imageId[i]);
        }

        return true;
    }
    @RequestMapping("mapsearch")
    public String mapsearch(){
        return "map";
    }


//    @GetMapping("/location")
//    public String hotelLocation(@RequestParam("id")int id,Model model){
//        City city=hotelService.findCityByPrimaryKey(id);
//        Province province=hotelService.findProvinceByPrimaryKey(city.getProvinceId());
//        Country country=hotelService.findCountryByPrimaryKey(province.getCountryId());
//        model.addAttribute("city",city);
//        model.addAttribute("province",province);
//        model.addAttribute("country",country);
//        return "hotelLocation";
//    }

    //PSY
    public List<Hotel> addHotelImage(List<Hotel> hotelList){
        List<Hotel> hotels=new ArrayList<>();
        for (Hotel hotel:hotelList
        ) {
            Hotel newHotel = hotelService.findHotelAndImageByPrimaryKey(hotel.getHotelId());
            hotels.add(newHotel);
        }
        return hotels;
    }

}
